package cn.tj212.xiaoyin.wechat.wxapi.controller;

import cn.tj212.xiaoyin.common.web.HttpHelper;
import cn.tj212.xiaoyin.wechat.wxapi.process.*;
import cn.tj212.xiaoyin.wechat.wxapi.service.MyService;
import cn.tj212.xiaoyin.wechat.wxapi.vo.AccountFans;
import cn.tj212.xiaoyin.wechat.wxapi.vo.MsgRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 微信与开发者服务器交互接口
 */
@Controller
@RequestMapping("/wxapi")
public class WxApiCtrl {

    @Autowired
    private MyService myService;

    /**
     * GET请求：进行url、token认证：
     * 1.将token、timestamp、nonce三个字段进行字典序排序
     * 2.将三个参数字符串拼接成一个字符串进行SHA1加密
     * 3.开发者获得加密后的字符串可与signature对比，标识该请求来自于微信
     * @param request
     * @return
     */
    @RequestMapping(value = "/message",method = RequestMethod.GET)
    @ResponseBody
    public String doGet(HttpServletRequest request){
        //根据url中的account参数获取相应的mpAccount处理即可
        MpAccount mpAccount= WxApiClient.getMpAccount();//获取公众号
        if (mpAccount!=null){
            String token=mpAccount.getToken();//获取token进行验证
            String signature=request.getParameter("signature");//微信加密签名
            String timestamp=request.getParameter("timestamp");//时间戳
            String nonce=request.getParameter("nonce");//随机数
            String echoStr=request.getParameter("echostr");//随机字符串

            //校验码返回成功，echostr，成功成为开发者，否则返回error，接入失败
            if (SignUtil.validSign(signature,token,timestamp,nonce)){
                return echoStr;
            }
        }
        return "error";
    }

    @RequestMapping(value = "/message",method = RequestMethod.POST)
    @ResponseBody
    public String doPost(HttpServletRequest request, HttpServletResponse response){
        //处理用户和公众号交互消息
        try {
            MsgRequest msgRequest= MsgXmlUtil.parseXml(request);//获取发送的消息
            String contextUri= HttpHelper.getContextHttpUri(request);
            return myService.processMsg(msgRequest,contextUri);
        }catch (Exception e){
            e.printStackTrace();
            return "error";
        }
    }

    /**
     * 测试微信OAuth认证
     * @param request
     * @return
     */
    @RequestMapping(value = "oauthTest")
    public ModelAndView oauthTest(HttpServletRequest request){
        MpAccount mpAccount=WxApiClient.getMpAccount();
        if (mpAccount!=null){
            ModelAndView mv=new ModelAndView("test/oauthTest");

            /**
             * 在拦截器OAuth2Interceptor中缓存了openID
             * 这里就可以直接取出
             */
            String openId= WxMemoryCacheClient.getOpenId(request.getSession().getId());
            if (null!=openId){
                AccountFans accountFans=WxApiClient.getAccountFans(openId);
                mv.addObject("openid",openId);
                mv.addObject("curUser",accountFans);
            }
            return mv;
        }else {
            ModelAndView mv=new ModelAndView("common/failure");
            mv.addObject("message","OAuth 获取openid失败");
            return mv;
        }
    }
}
